﻿var WxParse = require('../../wxParse/wxParse.js')
import api from '../../api/api'
import {
  banner
} from '../../api/conf'
import {
  homePro
} from '../../api/conf'
import {
  getcustomer
} from '../../api/conf'
import {
  cartCount
} from '../../api/conf'
import {
  cartallselected
} from '../../api/conf'
import {
  goodstocartbluk
} from '../../api/conf'
import {
  notice
} from '../../api/conf'
import {
  searCate
} from '../../api/conf'
import {
  weixinopenlogin
} from '../../api/conf'
import {
  homecategories
} from '../../api/conf'
import {
  checkshop
} from '../../api/conf'
var app = getApp()
Page({
  data: {
    swiperConfig: {},
    productlist: {},
    selec: [],
    total: 0,
    AdresList: null,
    showSelec: false,
    getIdAdres: false,
    noticeText: '',
    cate1: [],
    cate2: [],
    empowerShow: false,
    code: '',
    list: '',
    cateId: 101,
    banner2: '',
    indicatorDots: false,
    autoplay: false,
    interval: 5000,
    duration: 1000
  },
  onLoad: function(options) {
    var that = this
    if (options.code) {
      this.setData({
        code: options.code
      })
    }
    this.getBanner()
    this.getBanner2()
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {

            }
          })
        } else {
          that.setData({
            empowerShow: true
          })
        }
      }
    })
    this.getHomeCategories()
  },
  onReady: function() {
    this.getTip()
  },
  onShow: function() {
    if (wx.getStorageSync('guid')) {
      this.getCartNum()
    }
    this.getCate1()
    this.curAdres()
  },
  getBanner: function() {
    var that = this
    api.get(banner, {
      name: 'homehotbanner'
    }).then(res => {
      that.setData({
        swiperConfig: res.Data
      })
    })
  },
  getBanner2: function() {
    var that = this
    api.get(banner, {
      name: 'homehotbanner-second-mobile'
    }).then(res => {
      that.setData({
        banner2: res.Data.Items[0]
      })
    })
  },
  bannerHref: function(e) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url,
    })
  },
  //选中地址
  curAdres: function () {
    var that = this
    if (this.data.AdresList != app.globalData.currentAdress) {
      that.setData({
        AdresList: app.globalData.currentAdress
      })
    } else {
      var timer = setInterval(function () {
        if (that.data.AdresList != null) {
          clearInterval(timer)

          that.onLoad({})
        } else {
          that.setData({
            AdresList: app.globalData.currentAdress
          })
        }
      }, 100)
    }
    api.post(checkshop+'?Id='+app.globalData.currentAdress.Id).then(res => {})
  },
  getHomePro: function(code) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    var that = this
    api.get(homePro, {
      tagshow: true,
      code: code
    }).then(res => {
      that.setData({
        productlist: res
      })
      this.createArr(res.Data)
      wx.hideLoading()
    })
  },
  goDetail: function(event) {
    var detailId = event.currentTarget.dataset.detailid
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + detailId
    })
  },
  onShareAppMessage: function() {
    return {
      title: '创意商品个性化定制平台',
      path: '/pages/index/index?code=' + wx.getStorageSync('code')
    }
  },
  getCartNum: function() {
    api.get(cartCount, {}).then(res => {
      let num = ''
      if (res.Data == 0) {
        num = ''
      } else {
        num = res.Data
      }
      // wx.setTabBarBadge({
      //   index: 2,
      //   text: num
      // })
    })
  },
  getHomeCategories: function() {
    var that = this
    api.get(homecategories).then(res => {

      that.setData({
        list: res.Data
      })

    })
  },
  clickCart: function(e) {
    let arr = this.data.selec
    let index = e.currentTarget.dataset.index
    arr[index].show = true
    this.setData({
      selec: arr
    })
    this.compute()
  },
  clickAdd: function(e) {
    let arr = this.data.selec
    let index = e.currentTarget.dataset.index
    arr[index].qty++
      this.setData({
        selec: arr
      })
    this.compute()
  },
  clickReduce: function(e) {
    let arr = this.data.selec
    let index = e.currentTarget.dataset.index
    if (arr[index].qty > 1) {
      arr[index].qty--
    } else {
      arr[index].show = false
    }
    this.setData({
      selec: arr
    })
    this.compute()
  },
  goPay: function() {
    wx.showLoading({
      title: '正在结算',
      mask: true
    })
    let arr = this.data.selec
    let buyArr = []
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].show) {
        let obj = {
          PId: arr[i].proId,
          Qty: arr[i].qty,
        }
        buyArr.push(obj)
      }
    }
    api.post(cartallselected, {
      selected: false
    }).then(res => {
      api.post(goodstocartbluk, buyArr).then(res => {
        wx.hideLoading()
        wx.navigateTo({
          url: '/pages/checkout/checkout',
        })
      })
    })
  },
  onPullDownRefresh: function(e) {
    this.onShow()
    wx.stopPullDownRefresh();
  },
  createArr: function(res) {
    let arr = []
    let obj = {}
    let price = 0
    for (let i = 0; i < res.length; i++) {
      price = parseFloat((res[i].Price.Price).substr(1))
      obj = {
        proId: res[i].Id,
        show: false,
        qty: 1,
        price: price
      }
      arr.push(obj)
    }
    this.setData({
      selec: arr
    })
    this.compute()
  },
  compute: function() {
    let arr = this.data.selec
    let nums = 0
    let total = 0
    let show = false
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].show) {
        show = true
        nums = +(arr[i].qty * arr[i].price)
        total = total + nums
      }
    }
    this.setData({
      total: total.toFixed(2),
      showSelec: show
    })
  },
  gohref: function(e) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url,
    })
  },
  //选中地址
  curAdres: function() {
    var that = this
    if (this.data.AdresList != app.globalData.currentAdress) {
      that.setData({
        AdresList: app.globalData.currentAdress
      })
    } else {
      var timer = setInterval(function() {
        if (that.data.AdresList != null) {
          clearInterval(timer)
        } else {
          that.setData({
            AdresList: app.globalData.currentAdress
          })
        }
      }, 100)
    }
  },
  //获取地址id
  getAdressId: function(id) {
    var that = this
    if (this.data.getIdAdres) {
      return
    }
    var timer = setInterval(function() {
      if (app.globalData.location.length) {
        clearInterval(timer)
        for (let i = 0; i < app.globalData.location.length; i++) {
          if (id == app.globalData.location[i].adres.Id) {
            app.globalData.currentAdress = app.globalData.location[i].adres
            that.setData({
              AdresList: app.globalData.currentAdress
            })
          }
        }
        that.setData({
          getIdAdres: true
        })
      }
    }, 100)
  },
  //获取公告
  getTip: function() {
    var that = this
    api.get(notice, {
      systemName: 'notice'
    }).then(res => {
      that.setData({
        noticeText: res.Data.Body
      })
      var notice = res.Data.Body
      WxParse.wxParse('notice', 'html', notice, that, 5);
    })
  },
  getCate1: function() {
    var that = this
    api.get(searCate, {
      cid: 105,
      size: 20
    }).then(res => {
      var productlist = res.Data;
      that.setData({
        productlist: productlist
      })
    })
  },
  getCate2: function() {
    var that = this
    api.get(searCate, {
      cid: 101,
      size: 4
    }).then(res => {
      that.setData({
        cate2: res.Data.Items
      })
    })
  },
  bindGetUserInfo: function(e) {
    var that = this
    var guid = null
    if (wx.getStorageSync('guid')) {
      guid = wx.getStorageSync('guid')
    } else {
      guid = null
    }
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              wx.setStorageSync('nickName', res.userInfo.nickName)
              wx.showLoading({
                title: '登录中',
                mask: true
              })
              api.get(weixinopenlogin, {
                code: app.globalData.code,
                guid: guid,
                encryptedData: res.encryptedData,
                iv: res.iv,
                state: that.data.code
              }).then(res => {
                if (res.Code == 200) {
                  wx.setStorageSync('guid', res.Data.guid)
                  wx.setStorageSync('token', res.Data.token)
                  wx.setStorageSync('openId', res.Data.openId)
                  wx.showTabBar({})
                  that.setData({
                    empowerShow: false
                  })
                  wx.hideLoading()
                }
              })
            }
          })
        }
      }
    })
  },
  search: function(e) {
    wx.navigateTo({
      url: '/pages/search/search?q=' + e.detail.value,
    })
  },
  contactCallback: function(e) {
    var path = e.detail.path,
      query = e.detail.query,
      params = '';
    if (path) {
      for (var key in query) {
        params = key + '=' + query[key] + '&';
      }
      params = params.slice(0, params.length - 1);
      wx.navigateTo({
        url: path + '?' + params
      })
    }
  }
})